<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
        <el-form-item label="订单状态" prop="status">
          <el-radio-group v-model="queryParams.status" @change="handleQuery">
            <el-radio-button
              :key="-2"
              :label="-2"
            >
              全部
            </el-radio-button>
            <el-radio-button
              v-for="item in wms_shipment_status"
              :key="item.value"
              :label="item.value"
            >
              {{ item.label }}
            </el-radio-button>
            <!-- <el-radio-button
              v-for="item in wms_shipment_status"
              :key="item.value"
              :label="item.value">
              {{ item.label }}
            </el-radio-button> -->
          </el-radio-group>
        </el-form-item>

        <el-form-item label="订单单号" prop="order_id">
          <el-input
            v-model="queryParams.order_id"
            placeholder="请输入订单单号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="客户名称" prop="customer">
          <el-input
            v-model="queryParams.customer"
            placeholder="请输入客户名称"
            clearable
            @keyup.enter="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="mt20">

      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="6"><span style="font-size: large">订单</span></el-col>
        <el-col :span="1.5">
          <!-- 新增按钮 -->
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['wms:shipment:all']"
          >新增</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="shipmentOrderList" border class="mt20"
                @expand-change="handleExpandExchange"
                :row-key="getRowKey"
                :expand-row-keys="expandedRowKeys"
                empty-text="暂无订单"
                cell-class-name="vertical-top-cell">
      <!-- 订单明细 84To114 -->
        <el-table-column type="expand">
          <template #default="props">
            <div style="padding: 0 50px 20px 50px">
              <h3>订单明细</h3>
              <el-table :data="props.row.detail" v-loading="detailLoading[props.$index]" empty-text="暂无商品明细">
                <!-- <el-table-column label="明细ID">
                  <template #default="{ row }">
                    <div>{{ row?.detail_id }}</div>
                  </template>
                </el-table-column> -->
                <el-table-column label="订单单号">
                  <template #default="{ row }">
                    <div>单号：{{ row?.order_id }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="产品ID" prop="quantity" >
                  <template #default="{ row }">
                    <div>{{ row?.product_id }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="产品名称" prop="quantity" >
                  <template #default="{ row }">
                    <div>{{ row?.product_name }}</div>
                  </template>
                </el-table-column>
                <el-table-column label="产品数量" >
                  <template #default="{ row }">
                    <div>{{ row?.quantity }} (个)</div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单单号" align="left" min-width="120">
          <template #default="{ row }">
            <div>单号：{{ row.order_id }}</div>
            <!-- <div v-if="row.bizOrderNo">业务单号：{{ row.bizOrderNo }}</div> -->
          </template>
        </el-table-column>
        <el-table-column label="客户名称" align="left">
          <template #default="{ row }">
            <div>{{ row.customer }}</div>
          </template>
        </el-table-column>
        <el-table-column label="下单日期" align="left" min-width="100">
          <template #default="{ row }">
            <div class="flex-space-between">
              <div>{{ row.order_date }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" prop="status" width="80">
          <template #default="{ row }">
            <dict-tag :options="wms_shipment_status" :value="row.status" />
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remarks" />
        <el-table-column label="操作" align="right" class-name="small-padding fixed-width" width="180">
          <template #default="scope">
            <div>
              <el-popover
                placement="left"
                title="提示"
                :width="300"
                trigger="hover"
                :disabled="[-1,0,3].includes(scope.row.status)"
                :content="'订单【' + scope.row.order_id + '】已' + (scope.row.status === 1 ? '出库' : '作废' ) + '，无法修改！' "
                >
                <template #reference>
                  <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['wms:shipment:all']" :disabled="[1,2].includes(scope.row.status)">
                    修改
                  </el-button>
                </template>
              </el-popover>
              <el-button link type="primary" @click="handleGoDetail(scope.row)" v-hasPermi="['wms:shipment:all']">{{ expandedRowKeys.includes(scope.row.order_id) ? '收起' : '查看' }}
              </el-button>
              <el-popover
                placement="left"
                title="提示"
                :width="300"
                trigger="hover"
                :disabled="[-1,0].includes(scope.row.status)"
                :content="'订单【' + scope.row.order_id + '】已' + (scope.row.status === 1 ? '出库' : (scope.row.status === 2 ? '作废' : '驳回') )">
                <template #reference>
                  <el-button link type="primary" @click="Outbound(scope.row)" v-hasPermi="['wms:shipment:all']" :disabled="[-1,1,2,3].includes(scope.row.status)">出库</el-button>
                </template>
              </el-popover>
            </div>
            <div class="mt10">
              <el-popover
                placement="left"
                title="提示"
                :width="300"
                trigger="hover"
                :disabled="[-1,1,3,2].includes(scope.row.status)"
                :content="'订单【' + scope.row.order_id + '】已审核完成！' ">
                <template #reference>
                  <el-button link type="primary" @click="handleExamine(scope.row)" v-hasPermi="['wms:shipment:all']" :disabled="[0,1,2,3].includes(scope.row.status)">审核</el-button>
                </template>
              </el-popover>
              <el-popover
                placement="left"
                title="提示"
                :width="300"
                trigger="hover"
                :disabled="[-1,0,2,3].includes(scope.row.status)"
                :content="'订单【' + scope.row.order_id + '】已出库，无法删除！' ">
                <template #reference>
                  <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['wms:shipment:all']" :disabled="scope.row.status === 1">删除</el-button>
                </template>
              </el-popover>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-row>
        <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"/>
      </el-row>
    </el-card>
  </div>
</template>

<script setup name="ShipmentOrder">
import {getCurrentInstance, reactive, ref, toRefs} from "vue";
import {ElMessage} from "element-plus";
import {useWmsStore} from "../../../../store/modules/wms";
import {orderList ,orderDetailList , delorderdata, UpdateOrder, Updatebound } from "@/api/wms-order/product"
const { proxy } = getCurrentInstance();
// 画面--订单状态
const wms_shipment_status = ref([
  {
    label: '未审核',
    value: '-1'
  },
  {
    label: '未出库',
    value: '0'
  },
  {
    label: '已出库',
    value: '1'
  },
  {
    label: '作废',
    value: '2'
  },
  {
    label: '驳回',
    value: '3'
  }
])
const shipmentOrderList = ref([]);
const loading = ref(true);
const total = ref(0);
// 当前展开集合
const expandedRowKeys = ref([])
// 商品明细table的loading状态集合
const detailLoading = ref([])
const orderdata = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    order_id : undefined,
    customer : undefined,
    order_date : undefined,
    status : -2,
    remarks : undefined,
  }
})

const { queryParams } = toRefs(orderdata);

/** 查询入库单列表 */
function getList() {
  loading.value = true;
  const query = {...queryParams.value}
  if (query.status === -2) {
    query.status = null
  }
  orderList(query).then(response => {
    shipmentOrderList.value = response.data.rows;
    total.value = response.data.total;
    for (let i = 0; i < total; i++) {
      detailLoading.value.push(false)
    }
    expandedRowKeys.value = []
    loading.value = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  proxy.$router.push({ path: "/addOrder" });
}

// /** 删除按钮操作 */path: "/addOrder",  query: { id: row.order_id }
function handleDelete(row) {
  const _ids = row.order_id;
  proxy.$modal.confirm('确认删除订单【' + row.order_id + '】吗？').then(function() {
    loading.value = true;
    return delorderdata(_ids);
  }).then(() => {
    proxy.$modal.msgSuccess("删除成功");
  }).finally(() => {
    loading.value = false;
    getList();
  });
}
/** 修改按钮操作 */
function handleUpdate(row) {
  proxy.$router.push({ path: "/addOrder",  query: { id: row.order_id } });
}
/** 审核按钮 */
function handleExamine(row){
  proxy.$router.push({ path: "/examineOrder",  query: { id: row.order_id } });
}

/** 查看 */
function handleGoDetail(row) {
  const index = expandedRowKeys.value.indexOf(row.order_id)
  if (index !== -1) {
    // 收起
    expandedRowKeys.value.splice(index, 1)
  } else {
    // 展开
    expandedRowKeys.value.push(row.order_id)
    // loadShipmentOrderDetail(row)
  }
}

function handleExpandExchange(value, expandedRows) {
  if (!ifExpand(expandedRows)) {
    return
  }
  expandedRowKeys.value = expandedRows.map(it => it.order_id)
  //loadShipmentOrderDetail(value)
}

// function loadShipmentOrderDetail(row) {
//   const index = shipmentOrderList.value.findIndex(it => it.id === row.order_id)
//   detailLoading.value[index] = true
//   orderDetailList(row.order_id).then(res => {
//     if (res.data?.length) {
//       const details = res.data.map(it => {
//         return {
//           ...it,
//         }
//       })
//     }
//   }).finally(() => {
//     detailLoading.value[index] = false
//   })
// }

function ifExpand(expandedRows) {
  if (expandedRows.length < expandedRowKeys.value.length) {
    expandedRowKeys.value = expandedRows.map(it => it.id)
    return false;
  }
  return true
}

function getRowKey(row) {
  return row.order_id
}

function Outbound(row){
  getBound(row)
  upbound.value.forEach(
    element => {
      console.log(element)
      Updatebound(element)
    }
  )

  row.status = 1
  UpdateOrder(row.order_id,row).then((res) => {
    if (res.status === 200) {
      ElMessage.success('订单出库成功')
      getList()
    } else {
      ElMessage.error(res.msg)
    }
  }).finally(() => {
    loading.value = false
  })
}

const upbound = ref([]);

function getBound(row){
  upbound.value = []
  row.detail.forEach(it => {
    upbound.value.push({
      product_id: it.product_id,
      quantity: it.quantity
    })
  })
}

getList();
</script>
<style lang="scss">
.el-statistic__content {
  font-size: 14px;
}
.el-table .vertical-top-cell {
  vertical-align: top
}
</style>
